package com.billjc.activity.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

public class XmlUtil {
	public static Document builtDocument(String request){
		SAXBuilder builder = new SAXBuilder();
		Document document = null;
		// 报文转为Reader对象
		Reader in = new StringReader(request);
		try {
			document = builder.build(in);
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return document;
	}

	/**
	 * 根据xpath路径获取xml节点(多节点)
	 * 
	 * @param root
	 * @param path
	 * @return
	 * @throws JDOMException
	 */
	@SuppressWarnings("unchecked")
	public static List<Element> getElementsByPath(Element root, String path){
		List<Element> elements = null;
		try {
			elements = XPath.selectNodes(root, path);
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return elements;
	}

	/**
	 * 根据xpath路径获取xml节点(单节点)
	 * 
	 * @param root
	 * @param path
	 * @return
	 * @throws JDOMException
	 */
	public static Element getSingleElement(Element root, String path){
		Element element = null;
		try {
			element = (Element) XPath.selectSingleNode(root, path);
		} catch (JDOMException e) {
			
			e.printStackTrace();
		}
		return element;
	}
}
